package ptpconsumer;

import impl.BookDaoImpl;

import java.io.IOException;
import java.util.ArrayList;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import pojo.Book;

public class PtpConsumer {
	
	Book b;
	ArrayList<Book> booksList =new ArrayList<Book>();
	ObjectMapper mapper = new ObjectMapper();
	BookDaoImpl bdi = new BookDaoImpl();
	int m = 0;
	long start,end;
	public void run() throws Exception{
		ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
		Destination queue = new ActiveMQQueue("ZivTest");
		Connection conn = factory.createConnection();
		conn.start();
		Session sen = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
		
		
		MessageConsumer consumer = sen.createConsumer(queue);
		
		consumer.setMessageListener(new MessageListener() {
			
			public void onMessage(Message arg0) {
				if(m==0)start=System.currentTimeMillis(); 
				m++;
				
				TextMessage msg = (TextMessage)arg0;
				String jsonStr=null;
				try {
					jsonStr = msg.getText().toString();
					System.out.println(jsonStr);
					if(m==10000){
						end=System.currentTimeMillis(); 
						System.out.println((end-start)+"ms");
					}
				} catch (JMSException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				 
				try {
					b=mapper.readValue(jsonStr, Book.class);
				} catch (JsonParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (JsonMappingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				booksList.add(b);
				if(booksList.size()==1000){
					bdi.addBooksWithBatch(booksList);
					booksList.clear();
				}
			}
		});
	}
	public static void main(String[] args) throws Exception {
		new PtpConsumer().run();
	}
	
}
